package com.feeyo.groundservice.composewidget.view.drag_list.grid

import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.unit.dp

/**
 *作者：70893 on 2025-06-10
 *描述：网格列表拖拽
 */


/**
 * 网格列表拖拽
 *
 *@param items 列表数据
 * @param draggable 是否可拖拽
 * @param columCount 列数
 * @param onDragStart 拖拽开始回调
 * @param onDrag 拖拽时回调
 * @param  onDragEnd 拖拽结束回调
 * @param horizontalArrangement 水平排列方式
 * @param verticalArrangement 垂直排列方式
 * @param contentPadding 内边距
 * @param itemContent 列表项内容
 *
 * **/
@Composable
fun <T> DragDropLazyVerticalGrid(
    modifier: Modifier = Modifier,
    items: List<T>,
    draggable: Boolean = true,
    columCount: Int = 3,
    onDragStart: () -> Unit,
    onDrag: (Int, Int) -> Unit,
    onDragEnd: () -> Unit,
    horizontalArrangement: Arrangement.Horizontal = Arrangement.spacedBy(5.dp),
    verticalArrangement: Arrangement.Vertical = Arrangement.spacedBy(5.dp),
    contentPadding: PaddingValues = PaddingValues(5.dp),
    itemContent: (@Composable BoxScope.(modifier: Modifier, item: T, isDragging: Boolean) -> Any)
) {
    val gridState = rememberLazyGridState()
    val dragDropState = rememberGridDragDropState(gridState, onDragStart, onDrag, onDragEnd)

    LazyVerticalGrid(
        columns = GridCells.Fixed(columCount),
        modifier = Modifier.then(modifier).let {
            if (draggable) {
                it.dragContainer(dragDropState)
            } else
                it
        },
        state = gridState,
        contentPadding = contentPadding,
        verticalArrangement = verticalArrangement,
        horizontalArrangement = horizontalArrangement,
    ) {
        itemsIndexed(items, key = { _, item -> item.toString() }) { index, item ->
            DraggableItem(
                dragDropState = dragDropState,
                index = index,
            ) {
                val xScale = animateFloatAsState(
                    targetValue = if (it) 1.1f else 1f,
                    label = "size",
                )

                val yScale = animateFloatAsState(
                    targetValue = if (it) 1.1f else 1f,
                    label = "size",
                )

                val modifier = Modifier.scale(xScale.value, yScale.value)

                itemContent(modifier, item, it)
            }
        }
    }
}